package cn.sell.comm.result.handler;

import cn.sell.comm.result.DefaultErrorResult;
import cn.sell.comm.result.PlatformResult;
import cn.sell.comm.result.annotation.ResponseResult;
import cn.sell.comm.result.interceptor.ResponseResultInterceptor;
import cn.sell.comm.result.support.Result;
import cn.sell.comm.util.JsonUtil;
import cn.sell.comm.util.RequestContextHolderUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author Limi
 * @Description //TODO 接口响应体处理器
 * @Date 16:52 2019/7/11
 **/
@Log4j2
@ControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        HttpServletRequest request = RequestContextHolderUtil.getRequest();
        ResponseResult responseResultAnn = (ResponseResult) request
                .getAttribute(ResponseResultInterceptor.RESPONSE_RESULT);
        return responseResultAnn != null && !"NONE".equalsIgnoreCase(request.getHeader("Api-Style"));
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {
        ResponseResult responseResultAnn = (ResponseResult) RequestContextHolderUtil.getRequest()
                .getAttribute(ResponseResultInterceptor.RESPONSE_RESULT);
        Class<? extends Result> resultClazz = responseResultAnn.value();
        if (resultClazz.isAssignableFrom(PlatformResult.class)) {
            if (body instanceof DefaultErrorResult) {
                DefaultErrorResult defaultErrorResult = (DefaultErrorResult) body;
                PlatformResult platformResult = new PlatformResult();
                platformResult.setCode(Integer.valueOf(defaultErrorResult.getCode()));
                platformResult.setMessage(defaultErrorResult.getMessage());
                platformResult.setData(defaultErrorResult);
                return platformResult;
            } else if (body instanceof String) {
                return JsonUtil.toJson(PlatformResult.success(body));
            }
            return PlatformResult.success(body);
        }
        return body;
    }

}
